#!/bin/bash
source tools/getenv.sh


if [[ "$env" == "test" || "$env" == "prod" ]]; then
  if [[ ! -h $current_dir ]]; then
    echo -e "$BOLODRED $current_dir 不是软连，rollbackback命令仅支持软连$RESET"
    exit 1
  fi
  # 获取备份文件的个数
  backup_count=$(ls -1d "${real_app_root_path}.backup-"* 2>/dev/null | wc -l)

  # 如果没有备份文件，直接退出
  if [[ $backup_count -eq 0 ]]; then
    echo -e "$BOLODRED 没有备份文件,退出 $RESET"
    exit 0
  fi

  # 获取到最近的一个备份文件
  latest_backup=$(ls -1dr "${real_app_root_path}.backup-"* 2>/dev/null | head -n 1)
  echo "latest_backup = $latest_backup"
  echo "current_dir = $current_dir"
  # 把当前的软连指向这个

  rollbackStr="cd .. && rm -rf $current_dir && mv ${current_dir}.bak ${current_dir}"
  echo "mv $current_dir ${current_dir}.bak"
  mv "$current_dir" "${current_dir}.bak"
  echo "cd .. && ln -sf $latest_backup $app_root_path"
  cd .. && ln -sf "$latest_backup" "$app_root_path"
  ls -all "$current_dir"
  echo -e "$BOLODGREEN 回滚成功,后续请手动指向最新目录, , 或者运行 make rollbackback $RESET"

  rollbackAfterRestart

  echo "回滚命令："
  echo -e "$BOLODGREEN $rollbackStr $RESET"
  echo ""
else
  echo -e "$BOLD_WHITE $env 环境，不支持回滚 $RESET"
  exit 0
fi


echo "回滚最近备份完成"

# 软连存在的话，直接替换
# ln -sf dev.8080.conf service.conf